import { Op as op } from "sequelize"
import { Book } from "../model/Book.js"

let fn_lsit = async (ctx) => {
    let book = await Book.findAll({ where: {} })
    ctx.body = {
        data: book,
        msg: "列表成功",
        code: 1000
    }

}
let fn_ById = async (ctx) => {
    let id = ctx.params.id || 0
    let book = await Book.findByPk(id)
    ctx.body = {
        data: book,
        msg: "查询成功",
        code: 1000
    }
}
let fn_add = async (ctx) => {
    let obj = ctx.request.body
    if (obj) {
        await Book.create(obj)
    }
    console.log(obj);


    ctx.body = {
        data: obj,
        code: 1000,
        msg: "新增成功"
    }
}
let fn_upd = async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body || ""
    let res =await Book.update(obj, {
        where: { id: id }
    })
    ctx.body = {
        data: res,
        code: 1000,
        msg: "修改成功"
    }
}
let fn_del = async (ctx) => {
    let id = ctx.params.id || 0
    let count = await Book.destroy({
        where: {
            id: id
        }
    })
    let res
    if (count === 1) {
        res = {
            data: count,
            code: 1000,
            msg: "删除成功"
        }
    } else {
        res = {
            data: count,
            code: 4000,
            msg: "删除失败"
        }
    }
    ctx.body = res

}
export default [
    {
        fn: fn_lsit,
        url: "/book",
        method: "get"
    },
    {
        fn: fn_ById,
        url: "/book/:id",
        method: "get"
    },
    {
        fn: fn_add,
        url: "/book",
        method: "post"
    },
    {
        fn: fn_upd,
        url: "/book/:id",
        method: "put"
    },
    {
        fn: fn_del,
        url: "/book/:id",
        method: "del"
    },
]
